package com.docking.heylo.service.impl;

import com.docking.heylo.ThreadContext;
import com.docking.heylo.dao.entity.Coupon;
import com.docking.heylo.dao.mapper.CouponMapper;
import com.docking.heylo.enums.ECouponStatus;
import com.docking.heylo.service.ICouponService;
import com.docking.heylo.web.dto.CouponDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service
public class CouponServiceImpl implements ICouponService {

    @Resource
    private CouponMapper couponMapper;

    private String  baseCode = "1234567890abcedefghijklmnopqrstuvwxyz";


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void produce(CouponDto couponDto) {
        if(couponDto.getQuantity() == 0){
            couponDto.setQuantity(1);
        }

        for (int i = 0; i < couponDto.getQuantity(); i++){
            try{
                Coupon coupon = new Coupon();
                coupon.setCrtAt(new Date());
                coupon.setCrtBy(ThreadContext.userId());
                coupon.setPromoCode(generateCode());
                coupon.setStatus(ECouponStatus.create.getValue());
                coupon.setValue(couponDto.getValue());

                couponMapper.insertSelective(coupon);
            }catch (DuplicateKeyException e){
                i++;
            }
        }
    }

    @Override
    public PageInfo<Map<String, Object>> list(CouponDto couponDto) {
        PageHelper.startPage(couponDto.getPageNumber(), couponDto.getSize());
        return new PageInfo<>(couponMapper.list(couponDto.getPromoCode(), couponDto.getStatus()));
    }


    /***
     * 生成优惠码
     *
     * @return
     */
    public String generateCode(){
        Random random = new Random();
        StringBuilder sb = new StringBuilder(8);
        for (int i = 0; i < 8; i++){
            sb.append(baseCode.charAt(random.nextInt(baseCode.length())));
        }
        return sb.toString().toUpperCase();
    }
















}
